<template>
  <div class="collapse">
    <div
      class="item"
      v-for="(item, i) in list"
      :key="i"
      :style="`height: ${ currentIdx === i ? (titleHeightList[i] + contentHeightList[i]) : titleHeightList[i] }px`"
    >
      <div class="title" @click="onCollapse(i)">{{ item.title }}</div>
      <div class="content">{{ item.content }}</div>
    </div>
  </div>
</template>

<script>
export default {
  data () {
    return {
      currentIdx: 0,
      list: [
        {
          title: 'title 1',
          content: 'content 1 content 1 content 1 content 1 content 1 content 1 content 1 content 1 content 1 content 1 content 1 content 1 content 1 content 1 content 1 content 1 content 1 content 1 content 1 content 1 content 1 content 1 content 1 content 1 content 1 content 1 content 1 content 1 content 1',
        },
        {
          title: 'title 2 title 2 title 2 title 2 title 2 title 2 title 2 title 2 title 2 title 2 title 2 title 2 title 2 title 2 title 2 title 2 title 2 title 2 title 2 title 2 title 2 title 2 title 2 title 2 title 2 title 2 title 2 title 2 title 2 title 2 title 2 title 2 title 2 ',
          content: 'content 2',
        },
        {
          title: 'title 3',
          content: 'content 3',
        },
      ],
      titleHeightList: [],
      contentHeightList: [],
    };
  },
  methods: {
    onCollapse (i) {
      // 如果点击的是已经展开的当前项 则关闭当前项
      if (this.currentIdx === i) {
        this.currentIdx = -1;
      } else {
        // 否则展开当前项
        this.currentIdx = i;
      }
    },
    setHeightList () {
      // 获取所有content的高度
      const contentList = document.querySelectorAll('.collapse .content');
      this.contentHeightList = Array.from(contentList).map(el => el.offsetHeight);
      // 获取所有title的高度
      const titleList = document.querySelectorAll('.collapse .title');
      this.titleHeightList = Array.from(titleList).map(el => el.offsetHeight);
    },
  },
  mounted () {
    this.setHeightList();
    window.addEventListener('resize', this.setHeightList);
  },
  // 组件即将退出的时候
  beforeDestroy () {
    window.removeEventListener('resize', this.setHeightList);
  },
}
</script>

<style scoped>
.item {
  overflow: hidden;
  transition: all 1s;
}
.title {
  background-color: #f5f5f5;
  border-bottom: 1px solid #ccc;
}
.content {
  padding: 4px;
  box-sizing: border-box;
}

</style>